#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
from Scripts.Output import OutputElementConvert
from Scripts.Common import EnumType

#
# outputs config files to all of target folders
# @param [outputFolderUrls] target folders
# @param [excelConfigDatas] excel contents
#
def Run(outputFolderUrls, excelConfigDatas):
    for i in range(len(outputFolderUrls)):
        outputFolderUrl = outputFolderUrls[i]
        print("    [3." + str(i + 1) + "]" + outputFolderUrl)
        _DoRun(outputFolderUrl, excelConfigDatas)

#
# outputs config file to a target folder
# @param [outputFolderUrl] a target folder
# @param [excelConfigDatas] excel contents
#
def _DoRun(outputFolderUrl, excelConfigDatas):
    #output all of config files in turn
    excelCount = len(excelConfigDatas)
    for i in range(excelCount):
        excelConfigData = excelConfigDatas[i]


        excelContentStr = "{\r\n"

        #write the classify
        configClassify = excelConfigData.GetClassify()
        configClassifyInt = EnumType.ConvertToInt(configClassify)
        excelContentStr += "    \"Classify\" : " + str(configClassifyInt) + ", \r\n"

        #starts to write content string
        excelContentStr += "    \"Data\" : \r\n"
        excelContentStr += "    [\r\n"
        jsonOutputName = excelConfigData.GetOutputName()
        print("        " + jsonOutputName + ".json ...... ", end='')

        #writes all of line content string in turn
        excelLineCount = excelConfigData.GetLineCount()
        for j in range(excelLineCount):
            excelLineData = excelConfigData.GetLineData(j)

            #writes a line content
            excelContentStr += "        {"

            #writes all of data content in turn
            excelElementCount = excelLineData.GetCount()
            for k in range(excelElementCount):
                excelElementData = excelLineData.GetData(k)

                #convert element data to string data
                excelElementStr = OutputElementConvert.ConvertToString(excelElementData)
                excelElementName = excelElementData.GetName()
                if k + 1 == excelElementCount:
                    excelContentStr += "\"" + excelElementName + "\" : " + excelElementStr
                else:
                    excelContentStr += "\"" + excelElementName + "\" : " + excelElementStr + ", "
            
            if j + 1 == excelLineCount:
                excelContentStr += "}\r\n"
            else:
                excelContentStr += "},\r\n"
        excelContentStr += "    ]\r\n"
        excelContentStr += "}"

        #saves the config data to disk
        
        jsonOutputUrl = os.path.join(outputFolderUrl, jsonOutputName)
        jsonOutputUrl += ".json"
        fh = open(jsonOutputUrl, 'w', 1, "UTF-8")
        fh.write(excelContentStr)
        fh.close()

        print("OK")

    